package com.runa.monitor.platinterface.netservice.handler;

import com.runa.persistence.util.SpringContextUtil;
import com.runa.monitor.platinterface.netservice.equipment.NetEqu;
import com.runa.monitor.platinterface.platService.NetEquService;
import com.runa.protocol.dto.DtuReport;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthenticationHandler extends SimpleChannelInboundHandler<DtuReport> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DtuReport msg) {
        NetEquService netEquService = SpringContextUtil.getBean(NetEquService.class);
        NetEqu<String> netEqu = netEquService.getNetEquBySerial(msg.getData());
        if (netEqu != null) {
            if (msg.getClass().getName().contains("Report")) {
                if (NetEqu.getSerial(ctx.channel().id().asLongText()) == null) {
                    netEqu.register(ctx.channel());
                } else {
                    netEqu.heartbeatUpdate();
                }
            } else if (msg.getClass().getName().contains("Register")) {
                netEqu.register(ctx.channel());
            } else if (msg.getClass().getName().contains("Heart")) {
                netEqu.heartbeatUpdate();
                if (!netEqu.online()){
                    netEqu.register(ctx.channel());
                }
            } else if (msg.getClass().getName().contains("Electric")) {
                netEqu.heartbeatUpdate();
            }
        } else {
            log.debug("签权失败-非法客户端: {}", msg.getData());
            if (!(ctx.channel() instanceof NioDatagramChannel)) {
                ctx.channel().close().addListener(future -> {
                    if (future.isSuccess()) {
                        log.debug("关闭非法客户端连接：{} 成功", msg.getData());
                    } else {
                        log.debug("关闭非法客户端连接：{} 失败", msg.getData());
                    }
                });
            }
        }
    }
}
